package com.bj.barcode;

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

public class ScanCodeTask extends TimerTask {

	private static final int STATISTICS_SCHEDULE_HOUR = 0;
	private static boolean isRunning = false;
	Log logger = LogFactory.getLog(ScanCodeTask.class);
    private int xPos=0;
    private int yPos=0;
    private int width=0;
    private int length=0;
    private static final ThreadLocal<String> oldImageLocal = new ThreadLocal<String>();;
    private String  uuid;
    private  String localHost="0";
    private  String localPort="0";
    private  String idleImage=null;
    
	public ScanCodeTask(RobotPos pos,String localHost,String localPort) {
		this.localHost=localHost;
		this.localPort=localPort;
		//logger.info("ScanCodeTask:begin..."+this.localHost+this.localPort);
		this.xPos=pos.getxPos();
		this.yPos=pos.getyPos();
		this.width=pos.getWidth();
		this.length=pos.getLength();
		this.uuid=pos.getUuid();
	}

	@Override
	public void run() {
		if (!isRunning) {
			isRunning = true;
			executeTask();
			// 指定任务执行结束
			isRunning = false;
		} else {
			logger.info("previous ScanCodeTask not end");
		}
	}

	/**
	 * 执行任务,保存内存的数据进入系统！真相文本手工生成！放置到msg.js中！
	 */
	public void executeTask() {
		try {
			Robot robot=new Robot();
			//解析idle图像！
			File idle=new File(ConstantStri.idleImageName);
			BufferedImage  buffIdle=ImageIO.read(idle);
			ByteArrayOutputStream outIdle = new ByteArrayOutputStream(); 
			ImageIO.write(buffIdle, "PNG", outIdle); 
			byte[] bytesIdle = outIdle.toByteArray(); 
			String base64bytesIdle = Base64.encodeBytes(bytesIdle); 
			String base64ImageIdle = "data:image/png;base64," + base64bytesIdle; 

			
			Rectangle screenRect=new Rectangle(xPos,yPos,width,length);
			BufferedImage buff=robot.createScreenCapture(screenRect);
			
			ByteArrayOutputStream out = new ByteArrayOutputStream(); 
			ImageIO.write(buff, "PNG", out); 
			byte[] bytes = out.toByteArray(); 
			String base64bytes = Base64.encodeBytes(bytes); 
			String base64Image = "data:image/png;base64," + base64bytes;
			String oldImage=(String)oldImageLocal.get();
			if(oldImage==null){
				logger.info("ScanCodeTask: first execution!");
				oldImageLocal.set(base64Image);
			}else if(oldImage.equals(base64Image) || oldImage.equals(base64ImageIdle)){
				logger.info("ScanCodeTask: duplicated image found!"+System.currentTimeMillis());
				sendDupToSrv();
			}else{
				oldImageLocal.set(base64Image);
			}
		} catch (AWTException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		} 

	}
	public void sendDupToSrv(){
		   ClientMsg client=new ClientMsg();
			logger.info("ScanCodeTask:begin..."+this.localHost+this.localPort);
		   client.setRequestCommand("duplicatedImages");
		   client.setId(uuid);
		   client.setAgent("clickRobot");
		   client.setBase64ImageFlag(1);
		   //向服务器报告本机的ip地址和port，该参数是run.bat设置死了的
		   client.setRemoteIPAddress(this.localHost);
		   client.setRemotePort(this.localPort);
		   client.setRequestTime(0);
		   client.setResponseTime(0);
		   client.setResponseCommand("0");
		   client.setSubProtocol("0");
		   client.setBase64Image("0");
		   
		   Gson  json=new Gson();
		   ClientMsg[] clients=new ClientMsg[1];
		   clients[0]=client;
		   String uploadJSon=json.toJson(clients, ClientMsg[].class);
		   sendJsonToServer(ConstantStri.upLoadURL,uploadJSon);
		   //logger.info("AutoClickBarcode: clear code!"+uploadJSon);  
		
	}
    public String sendJsonToServer(String url, String jsonString){ 

        String response = null;
        DefaultHttpClient httpClient= null;
        try {
			httpClient = new DefaultHttpClient(); 
			
			HttpPost post = new HttpPost(url); 
			post.setHeader("Content-Type", "application/json"); 
			post.setEntity(new StringEntity(jsonString,"UTF-8")); 

			ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
			response = httpClient.execute(post,responseHandler);
			//logger.info(response);
		} catch (UnsupportedEncodingException e) {
			logger.error(e);
		} catch (ClientProtocolException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}finally{
			httpClient.getConnectionManager().shutdown();
		} 
        return response; 
    } 
}
